import base64
import pickle

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from carts import constants
from carts.serializers import CartSerializer, CartDeleteSerializer, CartSKUSerializer
from goods.models import SKU


class CartView(APIView):
    """购物车视图"""
    def perform_authentication(self, request):
        """
        重写父类的用户验证方法，不在进入视图前就检查JWT
        还是继续校验了，但是校验失败不会处理
        :param request:
        :return:
        """
        pass
    def post(self, request):
        """添加商品到购物车"""
        # 调用序列化器校验数据
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 判断用户是否已经登录了
        # 尝试对请求的用户进行验证
        try:
            user = request.user
        except Exception:
            # 验证失败，用户没有登录
            user = None
        # user.is_authenticated 为Ture, 表示当前访问者有登录权限
        # 如果登录了，则把用户提交的商品信息保存到redis中
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection("cart")
            pl = redis_conn.pipeline()
            # 保存购物车商品sku_id和数量到hash数据中
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            # 保存购物车商品勾选状态到set集合中
            pl.sadd('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_200_OK)

        else:
            # 如果未登录，则把用户提交的购物车信息存到cookie中
            """
            {
                sku_id: {'count':2, 'selected': True,}
            }
            """
            # 1. 获取request.COOKIE 中的购物车数据
            cart = request.COOKIES.get('cart')
            # 判断以前是否有添加商品到cookie购物车中
            if cart is None:
                # 如果没有，则默认就是空字典
                cart = {}
            else:
                # 如果有，则把字符串还原成字典
                cart = pickle.loads(base64.b64decode(cart))
            # 获取购物车制定当前sku_id的信息
            sku_dict = cart.get(sku_id)

            if sku_dict:
                count += int(sku_dict['count'])

            cart[sku_id] = {
                'count': count,
                'selected': selected,
            }
            cookie_cart = base64.b64encode(pickle.dumps(cart))

            # 响应前段附带cookie
            response = Response(serializer.data, status=status.HTTP_200_OK)
            response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRE)
            return response
    def get(self, request):
        """
        获取购物车中的商品列表
        :param request:
        :return:
        """
        print('________get in _________')
        # 判断是否登录， 选择从redis还是cookie中提取数据
        try:
            user = request.user
        except Exception:
            # 验证失败， 用户未登录
            user = None

        # 从购物车获取商品sku_id， 数量以及勾选状态
        if user is not None and user.is_authenticated:
            # 从redis中获取购物车
            # 用户已登录，从 redis中读取
            redis_conn =get_redis_connection('cart')
            redis_cart = redis_conn.hgetall('cart_%s' % user.id)
            redis_cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)
            """
            redis中数据是分散存储的，我们可以重新组装数据格式与cookie中的购物车数据保持一致，
            这样可以在返回数据时，两者共用一段代码
            """
            cart = {}
            for sku_id, count in redis_cart.items():
                cart[int(sku_id)]= {
                    'count': int(count),
                    'selected': sku_id in redis_cart_selected
                }
        else:
            # 获取 request.COOKIE 中的购物车数据
            cart = request.COOKIES.get('cart')
            # 判断以前是否有添加商品到cookie购物车中
            if cart is None:
                cart = {}
            else:
                # 如果有，则把字符串还原成字典
                cart = pickle.loads(base64.b64decode(cart))

        print(cart)
        # 遍历购物车，从数据库中提取前端需要的其他字段
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]['count']
            sku.selected = cart[sku.id]["selected"]

        serializer = CartSKUSerializer(instance=skus, many=True)

        return Response(serializer.data)

    def put(self, request):
        """更新购物城中的商品信息"""
        # 调用序列化器校验数据
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 判断用户是否已经登陆了
        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection("cart")
            pl = redis_conn.pipeline()
            # 保存购物车商品sku_id和数量到hash数据中
            pl.hset("cart_%s" % user.id, sku_id, count)
            # 保存购物车商品勾选状态到set集合中
            # 在更新的时候并不是每次状态都是勾选的，所以要判断一下。
            if selected:
                # select = True，则sadd表示添加一个成员
                pl.sadd("cart_selected_%s" % user.id, sku_id)
            else:
                # select = False，则srem表示移除一个成员
                pl.srem("cart_selected_%s" % user.id, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:
            # 从cookie中获取购物车
            # 1. 获取 request.COOKIE 中的购物车数据
            cart = request.COOKIES.get('cart')
            # 判断以前是否有添加商品到cookie购物车中
            if cart is None:
                # 如果没有，则默认就是空字典
                cart = {}
            else:
                # 如果有，则把字符串还原成字典
                cart = pickle.loads(base64.b64decode(cart))

            cart[sku_id] = {
                'count': count,
                'selected': selected
            }

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data)
            response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response

    def delete(self, request):
        """删除购物车中指定的商品"""
        serializer = CartDeleteSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data['sku_id']

        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录，在redis中删除
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 从购物车删除对应的hash成员 hdel
            pl.hdel("cart_%s" % user.id, sku_id)
            # 从勾选状态中删除对饮的set成员
            pl.srem("cart_selected_%s" % user.id, sku_id)
            pl.execute()
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            response = Response(serializer.data)

            # 用户未登录，在cookie中删除
            cart = request.COOKIES.get('cart')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))

                if sku_id in cart:
                    del cart[sku_id]

                    cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                    response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)

            return response